﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using GameView.Comment;
using GameView.Models;
using GameView.Services;
using GameView.Services.Comment;
using System.Collections.ObjectModel;

namespace GameView.ViewModels
{
    public partial class StatisticsByMeViewModel : ObservableObject
    {
        private RechargeToMService _service;

        private readonly ProjectService _proService;

        public StatisticsByMeViewModel(RechargeToMService service, ProjectService proService)
        {
            _service = service;
            _proService = proService;
            LoadDataAsync().ConfigureAwait(false);
            LoadPGAsync().ConfigureAwait(false);
        }

        [ObservableProperty]
        private ObservableCollection<StatisticsEntity> _listOne = [];

        [ObservableProperty]
        private bool _isFeatureEnabled = false;

        [ObservableProperty]
        private RechargeQueryDto _queryDto = new();

        [ObservableProperty]
        private ObservableCollection<string> _projectOptions = [];

        [ObservableProperty]
        private bool _isLoading = false;

        [ObservableProperty]
        private long _recharge = 0;

        [ObservableProperty]
        private long _withdrawal = 0;

        [ObservableProperty]
        private string _mainName = "商行统计";

        [ObservableProperty]
        private string _selectedProject;

         partial void OnSelectedProjectChanged(string value)
        {
            // 根据选择的项目重新加载游戏选项
            QueryDto.ProjectName = value;
        }

        private async Task LoadPGAsync()
        {
            try
            {
                var res = await _proService.GetAllAsync();
                ProjectOptions.Clear();
                foreach (var data in res.Data)
                {
                    ProjectOptions.Add(data.Name);
                }
            }
            catch (Exception ex)
            {
                GlobalMessage.Instance.ShowError($"数据加载错误：{ex.Message}");
                return;
            }
        }

        private async Task LoadDataAsync()
        {
            IsLoading = true;
            await Task.Delay(200);
            try
            {
                var p = await _service.GetByMerchantAsync(QueryDto);
                Recharge = p.Data.Sum(q => q.Recharge);
                Withdrawal = p.Data.Sum(q => q.Withdrawal);

                ListOne = [.. p.Data];
            }
            catch (Exception ex)
            {
                GlobalMessage.Instance.ShowError($"数据加载错误：{ex.Message}");
            }
            finally
            { IsLoading = false; }
        }

        [RelayCommand]
        private async Task SearchAsync()
        {
            await LoadDataAsync();
        }
    }
}